package top.lyc829.zzl_android.ui.team.my_team.travel;

import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.Serializable;
import java.util.List;

import okhttp3.internal.Util;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.TravelFragmentBinding;
import top.lyc829.zzl_android.logic.bean.SubTravelBean;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.team.my_team.MyTeamViewModel;
import top.lyc829.zzl_android.ui.travel.edit_travel.EditTravelActivity;

public class TravelFragment extends LazyFragment {

    private MyTeamViewModel mViewModel;
    private TravelFragmentBinding binding;

    BottomSheetDialog dialog;

    public static TravelFragment newInstance() {
        return new TravelFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = TravelFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(requireActivity()).get(MyTeamViewModel.class);
    }


    @Override
    public void lazyInit() {
        observer();
        clickListener();
    }

    private void clickListener() {
        binding.btnEditTravel.setOnClickListener(v -> {
            goEditTravel();
        });

        binding.myTeamTravelItem.getRoot().setOnLongClickListener(v -> {
            showBottomSheetDialog();
            return false;
        });

    }

    /**
     * 跳转到编辑游记界面
     */
    private void goEditTravel() {
        if (mViewModel.getTeamId().getValue() != null) {
            Intent intent = new Intent(getActivity(), EditTravelActivity.class);
            intent.putExtra("team_id", mViewModel.getTeamId().getValue());
            intent.putExtra("activities", (Serializable) mViewModel.getActivitiesLivaData().getValue());
            if (mViewModel.getTravelDetailLiveData().getValue() != null) {
                intent.putExtra("travel_detail", mViewModel.getTravelDetailLiveData().getValue());
            }
            startActivity(intent);
        } else {
            Utils.showToast("团队id未知");
        }
    }

    /**
     * 弹出底部弹窗
     */
    private void showBottomSheetDialog() {
        if (dialog == null) {
            dialog = new BottomSheetDialog(getContext(), R.style.MyBottomSheetDialog);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_layout_1, null);

            view.findViewById(R.id.linear_edit).setOnClickListener(v -> {
                goEditTravel();
                dialog.dismiss();
            });
            view.findViewById(R.id.linear_delete).setOnClickListener(v -> {
                deleteTravel();
                dialog.dismiss();
            });

            view.findViewById(R.id.linear_cancel).setOnClickListener(v -> {
                dialog.dismiss();
            });

            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
        }
        dialog.show();

    }

    /**
     * 删除游记
     */
    private void deleteTravel() {

        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
        } else if (mViewModel.getTeamId().getValue() == null) {
            Utils.showToast("删除失败");
            Utils.Sout("teamId未知");
        } else {
            mViewModel.deleteTravel(Utils.getUserId(), mViewModel.getTeamId().getValue());
        }

    }


    private void observer() {

        mViewModel.getTeamId().observe(getViewLifecycleOwner(), integer -> {
            mViewModel.getMyTeamInfo(integer);
            mViewModel.getActivityInTeam(integer);
            //mViewModel.loadTravelDetail(integer);
        });

        mViewModel.getTeamInfoBeanLiveData().observe(getViewLifecycleOwner(), myTeamInfoBean -> {
            binding.leaderUsername.setText(myTeamInfoBean.getLeader().getNickname());
            binding.myTeamName.setText(myTeamInfoBean.getName());
            binding.myTeamType.setText(getResources().getStringArray(R.array.team_type)[myTeamInfoBean.getType()]);
            binding.myTeamIntroduction.setText(myTeamInfoBean.getIntroduction());

            Glide.with(this)
                    .load(myTeamInfoBean.getHeaderImg())
                    .into(binding.myTeamHeaderImg);
            Glide.with(this)
                    .load(myTeamInfoBean.getLeader().getAvatarUrl())
                    .into(binding.leaderAvatar);

            if (!mViewModel.getTeamInfoBeanLiveData().getValue().getLeader().getId().equals(Utils.getUserId())) {
                binding.myTeamTravelItem.getRoot().setVisibility(View.GONE);
                binding.btnEditTravel.setVisibility(View.GONE);
            } else {
                mViewModel.loadTravelDetail(myTeamInfoBean.getId());
            }

        });

        mViewModel.getTravelDetailLiveData().observe(getViewLifecycleOwner(), travelDetailBean -> {

            if (travelDetailBean == null
                    || Utils.isStringEmpty(travelDetailBean.getTitle())
                    || (travelDetailBean.getContent() == null || travelDetailBean.getContent().size() <= 0)) {
                binding.myTeamTravelItem.getRoot().setVisibility(View.GONE);
            } else {
                binding.myTeamTravelItem.getRoot().setVisibility(View.VISIBLE);
                binding.myTeamTravelItem.travelsItemTitle.setText(travelDetailBean.getTitle());
                binding.myTeamTravelItem.travelsItemDescribe.setText(
                        RichUtils.returnOnlyText(getHoleTravelText(travelDetailBean.getContent())));

                Glide.with(this)
                        .load(RichUtils.returnImageUrlsFromHtml(getHoleTravelText(travelDetailBean.getContent())).get(0))
                        .into(binding.myTeamTravelItem.travelsItemImg);

            }

        });

    }

    private String getHoleTravelText(List<SubTravelBean> content) {
        StringBuilder builder = new StringBuilder();
        if (content != null) {
            for (SubTravelBean subTravel : content) {
                if (subTravel.getText() != null) {
                    builder.append(subTravel.getText()).append("<br>");
                }

            }
        }
        return builder.toString();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mViewModel.getTeamId().getValue() != null && mViewModel.getTeamInfoBeanLiveData().getValue() != null) {
            if (!mViewModel.getTeamInfoBeanLiveData().getValue().getLeader().getId().equals(Utils.getUserId())) {
                binding.myTeamTravelItem.getRoot().setVisibility(View.GONE);
                binding.btnEditTravel.setVisibility(View.GONE);
            } else {
                mViewModel.loadTravelDetail(mViewModel.getTeamId().getValue());
            }
        }

    }
}